#include "mainwindow.h"
#include "reminderdialog.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QTime>
#include <QTimer>
#include <QDebug>
#include <QMenu>
#include <QAction>
#include <QCloseEvent>
#include <QInputDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_timer(new QTimer(this))
    , m_trayIcon(nullptr)
    , m_trayMenu(nullptr)
{
    ui->setupUi(this);
    setWindowTitle("全屏定时提醒工具");
   this->setFixedSize(900, 700);
    
    // 设置全局字体抗锯齿和更好的字体
    QFont font = this->font();
    font.setFamily("Microsoft YaHei UI, Segoe UI, Arial, sans-serif");
    font.setHintingPreference(QFont::PreferFullHinting);
    font.setStyleStrategy(QFont::PreferAntialias);
    this->setFont(font);
    
    // 为整个应用程序设置抗锯齿样式
    this->setStyleSheet(this->styleSheet() + 
        "* { font-family: 'Microsoft YaHei UI', 'Segoe UI', Arial, sans-serif; }");

    // 初始化日期和时间控件
    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit->setMinimumDate(QDate::currentDate());
    ui->dateEdit->setMaximumDate(QDate::currentDate().addYears(1));
    
    QTime currentTime = QTime::currentTime();
    ui->hourSpinBox->setValue(currentTime.hour());
    ui->minuteSpinBox->setValue(currentTime.minute());

    // 注意：on_addButton_clicked槽函数会被Qt自动连接，无需手动连接
    
    // 连接设置密码按钮的信号
    connect(ui->setPasswordButton, &QPushButton::clicked, this, &MainWindow::setPassword);
    
    // 连接周期性选择改变的信号
    connect(ui->recurringComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &MainWindow::onRecurringChanged);
    
    // 连接提醒列表双击信号
    connect(ui->reminderListWidget, &QListWidget::itemDoubleClicked, 
            this, &MainWindow::onReminderItemDoubleClicked);
    
    // 设置列表控件的焦点策略，防止单击后失去焦点
    ui->reminderListWidget->setFocusPolicy(Qt::StrongFocus);
    ui->reminderListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    
    // 连接开机自启复选框信号
    connect(ui->autoStartCheckBox, &QCheckBox::toggled, this, &MainWindow::onAutoStartToggled);
    
    // 初始化开机自启复选框状态
    ui->autoStartCheckBox->setChecked(isAutoStartEnabled());
    
    // 连接快捷时间按钮的信号
    connect(ui->quickTime5Min, &QPushButton::clicked, this, &MainWindow::setQuickTime5Min);
    connect(ui->quickTime15Min, &QPushButton::clicked, this, &MainWindow::setQuickTime15Min);
    connect(ui->quickTime30Min, &QPushButton::clicked, this, &MainWindow::setQuickTime30Min);
    connect(ui->quickTime1Hour, &QPushButton::clicked, this, &MainWindow::setQuickTime1Hour);
    connect(ui->quickTime2Hour, &QPushButton::clicked, this, &MainWindow::setQuickTime2Hour);
    connect(ui->quickTimeTomorrow, &QPushButton::clicked, this, &MainWindow::setQuickTimeTomorrow);

    // 设置定时器，每秒检查一次是否有提醒到期[6](@ref)
    setupTimer();
    
    // 设置系统托盘
    setupTrayIcon();
    
    // 加载保存的提醒数据
    loadReminders();
    
    // 加载保存的密码
    QSettings settings("ReminderTool", "Settings");
    QString savedPassword = settings.value("password", "123456").toString();
    ReminderDialog::setPassword(savedPassword);
}

MainWindow::~MainWindow()
{
    // 保存提醒数据
    saveReminders();
    delete ui;
}


void MainWindow::setupTimer()
{
    connect(m_timer, &QTimer::timeout, this, &MainWindow::checkReminders);
    m_timer->start(1000); // 每隔1000毫秒（1秒）触发一次timeout信号[6](@ref)
}

void MainWindow::on_addButton_clicked()
{
    // 获取用户输入的事件内容
    QString message = ui->messageTextEdit->toPlainText().trimmed();

    if (message.isEmpty()) {
        QMessageBox::information(this, "提示", "待做事项不能为空哦！");
        return;
    }

    // 获取周期性设置
    bool isRecurring = ui->recurringComboBox->currentIndex() == 1;
    int recurringType = ui->recurringComboBox->currentIndex();
    
    // 构建提醒时间
    QDateTime reminderTime;
    if (isRecurring) {
        // 周期性任务：只使用时间，日期设为今天
        QDate today = QDate::currentDate();
        QTime selectedTime(ui->hourSpinBox->value(), ui->minuteSpinBox->value(), 0);
        reminderTime = QDateTime(today, selectedTime);
        
        // 如果设置的时间已经过了今天，则设为明天
        if (reminderTime <= QDateTime::currentDateTime()) {
            reminderTime = reminderTime.addDays(1);
        }
    } else {
        // 一次性任务：使用选择的日期和时间
        QDate selectedDate = ui->dateEdit->date();
        QTime selectedTime(ui->hourSpinBox->value(), ui->minuteSpinBox->value(), 0);
        reminderTime = QDateTime(selectedDate, selectedTime);
        
        // 检查时间是否已过
        if (reminderTime <= QDateTime::currentDateTime()) {
            QMessageBox::information(this, "提示", "请设置一个未来的时间。");
            return;
        }
    }
    
    // 创建新的提醒并添加到列表
    Reminder newReminder;
    newReminder.time = reminderTime;
    newReminder.message = message;
    newReminder.triggered = false;
    newReminder.isRecurring = isRecurring;
    newReminder.recurringType = recurringType;
    m_reminders.append(newReminder);

    // 更新界面上的提醒列表显示
    updateReminderListDisplay();
    
    // 保存提醒数据
    saveReminders();

    // 清空输入框，方便下次输入
    ui->messageTextEdit->clear();
    qDebug() << "提醒添加成功:" << reminderTime.toString("yyyy-MM-dd HH:mm:ss") << "-" << message;
}

void MainWindow::checkReminders()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    
    // 检查是否在免打扰时间内
    if (isDoNotDisturbActive()) {
        return; // 免打扰期间不检查提醒
    }
    
    for (int i = 0; i < m_reminders.size(); ++i) {
        Reminder &reminder = m_reminders[i];
        
        // 检查是否到达提醒时间且未触发
        if (currentTime >= reminder.time && !reminder.triggered) {
            // 获取倒计时设置
            int countdownSeconds = ui->countdownSpinBox->value();
            
            // 显示提醒对话框
            ReminderDialog *dialog = new ReminderDialog(reminder.message, countdownSeconds, this);
            dialog->setAttribute(Qt::WA_DeleteOnClose);
            dialog->show();
            
            // 标记为已触发
            reminder.triggered = true;
            
            // 如果是周期性任务，重置下次提醒时间
            if (reminder.isRecurring && reminder.recurringType == 1) { // 每天重复
                reminder.time = reminder.time.addDays(1);
                reminder.triggered = false; // 重置触发状态
            }
        }
    }
    
    // 移除已触发的非周期性任务
    for (int i = m_reminders.size() - 1; i >= 0; --i) {
        if (m_reminders[i].triggered && !m_reminders[i].isRecurring) {
            m_reminders.removeAt(i);
        }
    }
    
    // 更新显示和保存数据
    updateReminderListDisplay();
    saveReminders();
}

// 设置系统托盘
void MainWindow::setupTrayIcon()
{
    // 检查系统是否支持托盘
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(this, "系统托盘", "系统不支持托盘功能");
        return;
    }

    // 创建托盘图标
    m_trayIcon = new QSystemTrayIcon(this);
    // 使用应用程序默认图标，如果没有自定义图标的话
    m_trayIcon->setIcon(QIcon(":/avatar.jpg"));
    m_trayIcon->setToolTip("定时提醒工具");

    // 创建托盘菜单
    m_trayMenu = new QMenu(this);
    
    m_showAction = new QAction("显示主窗口", this);
    connect(m_showAction, &QAction::triggered, this, &MainWindow::showWindow);
    
    // 添加开机自启选项
    m_autoStartAction = new QAction("开机自启", this);
    m_autoStartAction->setCheckable(true);
    m_autoStartAction->setChecked(isAutoStartEnabled());
    connect(m_autoStartAction, &QAction::triggered, this, &MainWindow::toggleAutoStart);
    
    // 添加免打扰选项
    m_doNotDisturb2HAction = new QAction("免打扰 2小时", this);
    connect(m_doNotDisturb2HAction, &QAction::triggered, this, &MainWindow::toggleDoNotDisturb2Hours);
    
    m_doNotDisturb4HAction = new QAction("免打扰 4小时", this);
    connect(m_doNotDisturb4HAction, &QAction::triggered, this, &MainWindow::toggleDoNotDisturb4Hours);
    
    m_doNotDisturb8HAction = new QAction("免打扰 8小时", this);
    connect(m_doNotDisturb8HAction, &QAction::triggered, this, &MainWindow::toggleDoNotDisturb8Hours);
    
    m_disableDoNotDisturbAction = new QAction("关闭免打扰", this);
    connect(m_disableDoNotDisturbAction, &QAction::triggered, this, &MainWindow::disableDoNotDisturb);
    
    m_quitAction = new QAction("退出", this);
    connect(m_quitAction, &QAction::triggered, this, &MainWindow::quitApplication);
    
    // 构建菜单
    m_trayMenu->addAction(m_showAction);
    m_trayMenu->addSeparator();
    m_trayMenu->addAction(m_autoStartAction);
    m_trayMenu->addSeparator();
    m_trayMenu->addAction(m_doNotDisturb2HAction);
    m_trayMenu->addAction(m_doNotDisturb4HAction);
    m_trayMenu->addAction(m_doNotDisturb8HAction);
    m_trayMenu->addAction(m_disableDoNotDisturbAction);
    m_trayMenu->addSeparator();
    m_trayMenu->addAction(m_quitAction);
    
    // 更新免打扰菜单状态
    updateDoNotDisturbMenu();
    
    // 初始化托盘菜单状态
    m_autoStartAction->setChecked(isAutoStartEnabled());
    updateDoNotDisturbMenu();
    
    m_trayIcon->setContextMenu(m_trayMenu);
    
    // 连接托盘图标的激活信号
    connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::trayIconActivated);
    
    // 显示托盘图标
    m_trayIcon->show();
}

// 托盘图标激活处理
void MainWindow::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::DoubleClick:
        showWindow();
        break;
    default:
        break;
    }
}

// 显示窗口
void MainWindow::showWindow()
{
    show();
    raise();
    activateWindow();
}

// 退出应用程序
void MainWindow::quitApplication()
{
    saveReminders();
    QApplication::quit();
}

// 重写关闭事件
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (m_trayIcon && m_trayIcon->isVisible()) {
        hide();
        event->ignore();
        
        // 第一次最小化到托盘时提示用户
        static bool firstTime = true;
        if (firstTime) {
            m_trayIcon->showMessage("定时提醒工具", "程序已最小化到系统托盘", QSystemTrayIcon::Information, 2000);
            firstTime = false;
        }
    } else {
        event->accept();
    }
}

// 保存提醒数据
void MainWindow::saveReminders()
{
    QSettings settings("ReminderTool", "Reminders");
    settings.beginWriteArray("reminders");
    
    for (int i = 0; i < m_reminders.size(); ++i) {
        settings.setArrayIndex(i);
        settings.setValue("time", m_reminders[i].time);
        settings.setValue("message", m_reminders[i].message);
        settings.setValue("triggered", m_reminders[i].triggered);
        settings.setValue("isRecurring", m_reminders[i].isRecurring);
        settings.setValue("recurringType", m_reminders[i].recurringType);
    }
    
    settings.endArray();
    
    // 保存倒计时设置
    settings.setValue("countdownSeconds", ui->countdownSpinBox->value());
}

// 加载提醒数据
void MainWindow::loadReminders()
{
    QSettings settings("ReminderTool", "Reminders");
    int size = settings.beginReadArray("reminders");
    
    m_reminders.clear();
    
    for (int i = 0; i < size; ++i) {
        settings.setArrayIndex(i);
        Reminder reminder;
        reminder.time = settings.value("time").toDateTime();
        reminder.message = settings.value("message").toString();
        reminder.triggered = settings.value("triggered").toBool();
        reminder.isRecurring = settings.value("isRecurring", false).toBool();
        reminder.recurringType = settings.value("recurringType", 0).toInt();
        
        // 对于周期性任务，如果时间已过且已触发，自动调整到下次时间
        if (reminder.isRecurring && reminder.triggered && reminder.recurringType == 1) {
            QDateTime currentTime = QDateTime::currentDateTime();
            while (reminder.time <= currentTime) {
                reminder.time = reminder.time.addDays(1);
            }
            reminder.triggered = false; // 重置触发状态
        }
        
        // 只加载未来的或周期性的提醒
        if (reminder.time > QDateTime::currentDateTime() || reminder.isRecurring) {
            m_reminders.append(reminder);
        }
    }
    
    settings.endArray();
    
    // 加载倒计时设置
    int savedCountdown = settings.value("countdownSeconds", 10).toInt(); // 默认10秒
    ui->countdownSpinBox->setValue(savedCountdown);
    
    updateReminderListDisplay();
}

// 设置密码
void MainWindow::setPassword()
{
    bool ok;
    QString currentPassword = ReminderDialog::getPassword();
    
    // 如果不是默认密码，先验证当前密码
    if (currentPassword != "123456") {
        QString inputCurrentPassword = QInputDialog::getText(this, "验证当前密码", 
                                                           "请输入当前密码:", 
                                                           QLineEdit::Password, 
                                                           "", &ok);
        if (!ok || inputCurrentPassword != currentPassword) {
            QMessageBox::warning(this, "密码错误", "当前密码不正确！");
            return;
        }
    }
    
    // 输入新密码
    QString newPassword = QInputDialog::getText(this, "设置新密码", 
                                              "请输入新密码:", 
                                              QLineEdit::Password, 
                                              "", &ok);
    if (!ok || newPassword.isEmpty()) {
        return;
    }
    
    // 确认新密码
    QString confirmPassword = QInputDialog::getText(this, "确认新密码", 
                                                  "请再次输入新密码:", 
                                                  QLineEdit::Password, 
                                                  "", &ok);
    if (!ok || confirmPassword != newPassword) {
        QMessageBox::warning(this, "密码不匹配", "两次输入的密码不一致！");
        return;
    }
    
    // 设置新密码
    ReminderDialog::setPassword(newPassword);
    
    // 保存密码到设置中
    QSettings settings("ReminderTool", "Settings");
    settings.setValue("password", newPassword);
    
    QMessageBox::information(this, "设置成功", "密码设置成功！");
}

void MainWindow::updateReminderListDisplay()
{
    // 保存当前选中的项目索引
    int currentRow = ui->reminderListWidget->currentRow();
    
    ui->reminderListWidget->clear();
    
    for (const Reminder &reminder : m_reminders) {
        // 创建更美观的显示格式
        QString timeStr = reminder.time.toString("MM-dd hh:mm");
        QString typeStr;
        QString typeIcon;
        
        if (reminder.isRecurring) {
            if (reminder.recurringType == 1) {
                typeStr = "每天重复";
                typeIcon = "🔄";
            }
        } else {
            typeStr = "一次性";
            typeIcon = "⏰";
        }
        
        // 使用更现代的格式：图标 + 时间 | 内容 (类型)
        QString displayText = QString("%1 %2 | %3 (%4)")
                             .arg(typeIcon)
                             .arg(timeStr)
                             .arg(reminder.message)
                             .arg(typeStr);
        
        QListWidgetItem *item = new QListWidgetItem(displayText);
        
        // 为不同类型的提醒设置不同的图标颜色提示
        if (reminder.isRecurring) {
            item->setData(Qt::UserRole, "recurring");
        } else {
            item->setData(Qt::UserRole, "oneshot");
        }
        
        ui->reminderListWidget->addItem(item);
    }
    
    // 恢复选中状态（如果之前有选中的项目且索引仍然有效）
    if (currentRow >= 0 && currentRow < ui->reminderListWidget->count()) {
        ui->reminderListWidget->setCurrentRow(currentRow);
    }
}

// 快捷时间设置函数
void MainWindow::setQuickTime5Min()
{
    QDateTime quickTime = QDateTime::currentDateTime().addSecs(5 * 60);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

void MainWindow::setQuickTime15Min()
{
    QDateTime quickTime = QDateTime::currentDateTime().addSecs(15 * 60);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

void MainWindow::setQuickTime30Min()
{
    QDateTime quickTime = QDateTime::currentDateTime().addSecs(30 * 60);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

void MainWindow::setQuickTime1Hour()
{
    QDateTime quickTime = QDateTime::currentDateTime().addSecs(60 * 60);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

void MainWindow::setQuickTime2Hour()
{
    QDateTime quickTime = QDateTime::currentDateTime().addSecs(2 * 60 * 60);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

void MainWindow::setQuickTimeTomorrow()
{
    QDateTime quickTime = QDateTime::currentDateTime().addDays(1);
    ui->dateEdit->setDate(quickTime.date());
    ui->hourSpinBox->setValue(quickTime.time().hour());
    ui->minuteSpinBox->setValue(quickTime.time().minute());
}

// 周期性选择改变的槽函数
void MainWindow::onRecurringChanged()
{
    bool isRecurring = ui->recurringComboBox->currentIndex() == 1;
    
    // 如果是周期性任务，禁用日期选择
    ui->dateEdit->setEnabled(!isRecurring);
    
    if (isRecurring) {
        // 周期性任务时，将日期设为今天（仅作显示用）
        ui->dateEdit->setDate(QDate::currentDate());
    }
}

void MainWindow::onReminderItemDoubleClicked(QListWidgetItem *item)
{
    if (!item) return;
    
    int row = ui->reminderListWidget->row(item);
    if (row < 0 || row >= m_reminders.size()) return;
    
    // 确认删除
    QString reminderText = QString("%1 - %2")
                          .arg(m_reminders[row].time.toString("yyyy-MM-dd hh:mm:ss"))
                          .arg(m_reminders[row].message);
    
    int ret = QMessageBox::question(this, "删除提醒", 
                                   QString("确定要删除以下提醒吗？\n\n%1").arg(reminderText),
                                   QMessageBox::Yes | QMessageBox::No,
                                   QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 删除提醒
        m_reminders.removeAt(row);
        
        // 更新显示和保存数据
        updateReminderListDisplay();
        saveReminders();
        
        QMessageBox::information(this, "删除成功", "提醒已成功删除！");
    }
}

// 开机自启相关函数实现
bool MainWindow::isAutoStartEnabled()
{
    QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    return settings.contains("ReminderTool");
}

void MainWindow::setAutoStart(bool enabled)
{
    QSettings settings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    
    if (enabled) {
        QString appPath = QCoreApplication::applicationFilePath();
        appPath = QDir::toNativeSeparators(appPath);
        settings.setValue("ReminderTool", appPath);
    } else {
        settings.remove("ReminderTool");
    }
}

void MainWindow::toggleAutoStart()
{
    bool currentState = isAutoStartEnabled();
    setAutoStart(!currentState);
    m_autoStartAction->setChecked(!currentState);
    
    QString message = !currentState ? "已启用开机自启" : "已禁用开机自启";
    if (m_trayIcon) {
        m_trayIcon->showMessage("开机自启", message, QSystemTrayIcon::Information, 2000);
    }
}

// 免打扰相关函数实现
bool MainWindow::isDoNotDisturbActive()
{
    if (!m_doNotDisturbEndTime.isValid()) {
        return false;
    }
    
    QDateTime currentTime = QDateTime::currentDateTime();
    if (currentTime >= m_doNotDisturbEndTime) {
        m_doNotDisturbEndTime = QDateTime(); // 清除过期的免打扰时间
        updateDoNotDisturbMenu();
        return false;
    }
    
    return true;
}

void MainWindow::updateDoNotDisturbMenu()
{
    bool isActive = isDoNotDisturbActive();
    
    m_doNotDisturb2HAction->setEnabled(!isActive);
    m_doNotDisturb4HAction->setEnabled(!isActive);
    m_doNotDisturb8HAction->setEnabled(!isActive);
    m_disableDoNotDisturbAction->setEnabled(isActive);
    
    if (isActive) {
        QString timeStr = m_doNotDisturbEndTime.toString("hh:mm");
        m_disableDoNotDisturbAction->setText(QString("关闭免打扰 (至%1)").arg(timeStr));
    } else {
        m_disableDoNotDisturbAction->setText("关闭免打扰");
    }
}

void MainWindow::toggleDoNotDisturb2Hours()
{
    m_doNotDisturbEndTime = QDateTime::currentDateTime().addSecs(2 * 3600);
    updateDoNotDisturbMenu();
    
    if (m_trayIcon) {
        m_trayIcon->showMessage("免打扰", "已启用2小时免打扰模式", QSystemTrayIcon::Information, 2000);
    }
}

void MainWindow::toggleDoNotDisturb4Hours()
{
    m_doNotDisturbEndTime = QDateTime::currentDateTime().addSecs(4 * 3600);
    updateDoNotDisturbMenu();
    
    if (m_trayIcon) {
        m_trayIcon->showMessage("免打扰", "已启用4小时免打扰模式", QSystemTrayIcon::Information, 2000);
    }
}

void MainWindow::toggleDoNotDisturb8Hours()
{
    m_doNotDisturbEndTime = QDateTime::currentDateTime().addSecs(8 * 3600);
    updateDoNotDisturbMenu();
    
    if (m_trayIcon) {
        m_trayIcon->showMessage("免打扰", "已启用8小时免打扰模式", QSystemTrayIcon::Information, 2000);
    }
}

void MainWindow::disableDoNotDisturb()
{
    m_doNotDisturbEndTime = QDateTime();
    updateDoNotDisturbMenu();
    
    if (m_trayIcon) {
        m_trayIcon->showMessage("免打扰", "已关闭免打扰模式", QSystemTrayIcon::Information, 2000);
    }
}

void MainWindow::onAutoStartToggled(bool checked)
{
    setAutoStart(checked);
    QString message = checked ? "已启用开机自启" : "已禁用开机自启";
    if (m_trayIcon) {
        m_trayIcon->showMessage("开机自启", message, QSystemTrayIcon::Information, 2000);
    }
}
